package sources;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * A class representing an iCal component.
 *
 * @author Alana Meditz
 * @author Ty Yago
 * @author Katherine Kishaba
 * @author Jimmy CUmming
 * 
 */
public class ICalComponent {
	
	private final String DATEFORMAT = "yyyyMMdd'T'HHmmss'Z'";
	
	private String type;
	private List<ICalProperty> componentProperties = new ArrayList<ICalProperty>();
	
	/**
	 * ICalComponent constructor.  Sets required properties.
	 * 
	 * @param type String containing the type of iCal component to be represented
	 */
	public ICalComponent(String type) {
		this.type = type;
		String dtstamp = currentTimeUTC();
		componentProperties.add(new ICalProperty("DTSTAMP", dtstamp));
		componentProperties.add(new ICalProperty("UID", getUID(dtstamp)));
	}
	
	/**
	 * Adds a property to the component's property list
	 * 
	 * @param name  String name of new property
	 * @param value String value of new property
	 */
	public void addComponentProperty(String name, String value) {
		componentProperties.add(new ICalProperty(name, value));
	}
	
	/**
	 * Helper method used by constructor to set UID property.
	 * 
	 * @param dtstamp String of current UTC time
	 * @return        String UID
	 */
	private String getUID(String dtstamp) {
		String hostname = "";
		byte[] ipAddr = new byte[0];
		try {
		    InetAddress addr = InetAddress.getLocalHost();
		    ipAddr = addr.getAddress();
		    hostname = addr.getHostName();
		} catch (UnknownHostException e) {
		}
		
		return dtstamp + "@" + hostname + "@" + ipAddr;
	}
	
	/**
	 * Helper method used by constructor.  Returns the current time in UTC format as a String.
	 * 
	 * @return Current time in UTC
	 */
	private String currentTimeUTC() {
		final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
		sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
		final String utcTime = sdf.format(new Date());
		
		return utcTime;
	}
	
	/**
	 * @return Type of this ICalComponent
	 */
	public String getType() {
		return type;
	}
	
	/**
	 * @return ICalProperties of this ICalComponent
	 */
	public List<ICalProperty> getComponentProperties() {
		return componentProperties;
	}
}